import React, { useState } from 'react';
import { Search } from 'react-vant';
import './ExecutorSelect.css';

const ExecutorSelect = ({ value = [], onChange }) => {
  const [searchValue, setSearchValue] = useState('');
  const [searchResults, setSearchResults] = useState([]);

  // 模拟所有可选的执行人数据
  const allExecutors = [
    { name: '于伟航', avatar: '/avatars/1.png' },
    { name: '小张', avatar: '/avatars/2.png' },
    { name: '严瑞元', avatar: '/avatars/3.png' },
    { name: '卢旭元', avatar: '/avatars/4.png' },
    { name: '王一月', avatar: '/avatars/5.png' },
    { name: '李鹤轩', avatar: '/avatars/6.png' },
    { name: '张伟成', avatar: '/avatars/7.png' },
  ];

  // 搜索处理
  const handleSearch = (val) => {
    setSearchValue(val);
    if (val.trim()) {
      const results = allExecutors.filter(
        exec => exec.name.includes(val.trim())
      );
      setSearchResults(results);
    } else {
      setSearchResults([]);
    }
  };

  // 选择执行人
  const handleSelect = (executor) => {
    if (!value.find(item => item.name === executor.name)) {
      onChange([...value, executor]);
    }
    setSearchValue('');
    setSearchResults([]);
  };

  // 删除执行人
  const handleRemove = (name) => {
    const newValue = value.filter(item => item.name !== name);
    onChange(newValue);
  };

  return (
    <div className="executor-select">
      <div className="section-title">执行人</div>
      
      {/* 搜索框 */}
      <Search
        value={searchValue}
        onChange={handleSearch}
        placeholder="搜索"
        shape="round"
        background="#f7f8fa"
      />

      {/* 搜索结果列表 */}
      {searchResults.length > 0 && (
        <div className="search-results">
          {searchResults.map((executor) => (
            <div 
              key={executor.name} 
              className="result-item"
              onClick={() => handleSelect(executor)}
            >
              <img 
                src={executor.avatar} 
                alt="" 
                className="executor-avatar"
              />
              <span className="executor-name">{executor.name}</span>
            </div>
          ))}
        </div>
      )}

      {/* 已选择的执行人列表 */}
      <div className="selected-executors">
        {value.map((executor) => (
          <div key={executor.name} className="executor-tag">
            <img 
              src={executor.avatar} 
              alt="" 
              className="executor-avatar"
            />
            <span className="executor-name">{executor.name}</span>
            <span 
              className="remove-icon" 
              onClick={() => handleRemove(executor.name)}
            >
              ×
            </span>
          </div>
        ))}
      </div>
    </div>
  );
};

export default ExecutorSelect;